package auth

import (
	"net/http"

	"github.com/sirupsen/logrus"
	"github.com/wi-cuckoo/eastlake/util"
)

// HandleAuthentication is a middleware that authenticate the http request
func HandleAuthentication(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		logrus.Debugf("HandleAuthentication ... ")
		// 放开 /login 登陆的权限校验, 避免死循环
		if r.URL.Path != "/login" {
			username := util.GetCookie(r, "username")
			if username != "" {
				logrus.Debugf("current login user: %s\n", username)
			} else {
				logrus.Debugf("user not login, please login first!\n")
				http.Redirect(w, r, "/login", http.StatusFound)
			}
		}
		next.ServeHTTP(w, r)
	})
  }